package base.thread.saleTicket;

import java.util.Vector;

public class Ticket {
	public int ticketNum = 100;
	private boolean isConsumer = false;
	private Vector<Integer> numVector = new Vector<Integer>();

	public synchronized void saleTicket() {
		if (!isConsumer) {
			try {
				wait();
			} catch (Exception e) {
				e.printStackTrace();
			}
		}
		if (ticketNum > 0) {
			System.out.println(Thread.currentThread().getName() + "卖给"
					+ getConsumerName() + "一张票,票号为:" + ticketNum-- + "票");
		}
		try {
			Thread.sleep(10);
		} catch (Exception e) {
			e.printStackTrace();
		}
	}

	public synchronized void getConsumer() {
		if (isConsumer) {
			try {
				wait();
			} catch (Exception e) {
				e.printStackTrace();
			}
		}
		// 判断票是否已经售完
		if (ticketNum == 0) {
			System.out.println("对不起,今天的票已售完,请明天早点来！");
		}
		try {
			Thread.sleep(10);
		} catch (InterruptedException e) {
			e.printStackTrace();
		}
		isConsumer = true;
		notify();
	}

	public String getConsumerName() {
		int num = Integer.valueOf((int) (Math.random() * 999 + 1));
		String consumerName = "顾客" + num;
		// 判断是否有人重复买票
		while (numVector.contains(num)) {
			System.out.println("对不起," + consumerName + " ,您已经买了一张票,不能再买一张了");
			num = Integer.valueOf((int) (Math.random() * 999 + 1));
		}
		numVector.add(num);
		return consumerName;
	}

}
